package com.jzqf.androidserver;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.yanzhenjie.andserver.annotation.GetMapping;
import com.yanzhenjie.andserver.annotation.PostMapping;
import com.yanzhenjie.andserver.annotation.RequestParam;
import com.yanzhenjie.andserver.annotation.RestController;
import com.yanzhenjie.andserver.http.HttpMethod;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.http.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class UserController {

    public static void allow(HttpResponse response, HttpMethod... methods) {
        String methodHeader = TextUtils.join(",", methods);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", methodHeader);
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Allow", methodHeader);
    }

    @PostMapping(path = "/user/login", consumes = "application/json; charset=utf-8")
    String login(@RequestParam("account") String account,
                 @RequestParam("password") String password) {
        if ("123".equals(account) && "123".equals(password)) {
            return "Login successful.";
        } else {
            return "Login failed.";
        }

    }

    @GetMapping(path = "/user/getUser", consumes = "application/json; charset=utf-8")
    String login() {

        return "user is here!";
    }

    @PostMapping("/user/upload")
    String upload(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            String tag = "http";
            Log.i(tag, "upload:");
            String filename = file.getFilename();
            Log.i(tag, "fileName:" + filename);
            File localFile = FileUtil.createRandomFile(ContextApp.app(), file);
            // Create a file at the target location.
            file.transferTo(localFile);
            // Transfer the file to the target location.
            return localFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return "异常" + e.getMessage();
        }

    }

    @PostMapping(path = "/user/uploadFile")
    String uploadFile(@RequestParam("file") String file) throws IOException {
        try {
            String tag = "http";
            Log.i(tag, "upload:");
            Bitmap bitmap = FileUtil.toBitmap(file);
            FileUtil.saveImageToGallery(bitmap);
            // Transfer the file to the target location.
            return "localFile.getAbsolutePath()";
        } catch (Exception e) {
            e.printStackTrace();
            return "异常" + e.getMessage();
        }

    }
}
